//
//  GQHEnterpriseAuthorizationController.m
//  Xanthium
//
//  Created by GuanQinghao on 31/03/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#pragma mark Macro
#import "GQHHeader.h"

#pragma mark Model

#pragma mark Object

#pragma mark View
#import "GQHEnterpriseAuthorizationView.h"
#import "GQHCustomCell.h"

#pragma mark Controller
#import "GQHEnterpriseAuthorizationController.h"
#import "GQHAgreementController.h"

#pragma mark CocoaPods
#import <TZImagePickerController.h>

#pragma mark ----------Header End----------

@interface GQHEnterpriseAuthorizationController () <GQHEnterpriseAuthorizationViewDelegate,TZImagePickerControllerDelegate> {
    
#pragma mark Data
    /// 参数
    UIImage *image0;
    UIImage *image1;
    NSMutableDictionary *parameters;
#pragma mark View
    /// 自定义根视图
    GQHEnterpriseAuthorizationView *rootView;
}

@end


@implementation GQHEnterpriseAuthorizationController

#pragma mark --Lifecycle
- (void)loadView {
    DLog();
    
    rootView = [[GQHEnterpriseAuthorizationView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    rootView.qh_delegate = self;
    self.view = rootView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog();
    
    parameters = [NSMutableDictionary dictionary];
    [parameters setObject:USER_GET_ID forKey:@"userId"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    DLog();
    
    self.qh_titleLabel.text = @"物流企业认证信息";
    [self.qh_rightButton setHidden:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    DLog();
    
}

#pragma mark --Delegate
- (void)qh_selectedRowWithTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
            
        case 0: {
            
            /// 公司名称
            [self qh_alertWithTitle:@"请输入公司名称" message:nil inputHandler:^(UITextField * _Nullable textField) {
                
                textField.placeholder = @"请输入公司名称";
                
            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
                
                UITextField *inputTextField = alertController.textFields.firstObject;
                if (inputTextField.text.length > 0) {
                    
                    [parameters setObject:inputTextField.text forKey:@"companyName"];
                    [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:0];
                    [rootView.qh_tableView reloadData];
                }
            } completion:nil];
        }
            break;
        case 1: {
            
            /// 公司地址
            [self qh_alertWithTitle:@"请输入公司地址" message:nil inputHandler:^(UITextField * _Nullable textField) {
                
                textField.placeholder = @"请输入公司地址";
                
            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
                
                UITextField *inputTextField = alertController.textFields.firstObject;
                if (inputTextField.text.length > 0) {
                    
                    [parameters setObject:inputTextField.text forKey:@"companyAdd"];
                    [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:1];
                    [rootView.qh_tableView reloadData];
                }
            } completion:nil];
        }
            break;
        case 2: {
            
            /// 联系人
            [self qh_alertWithTitle:@"请输入联系人" message:nil inputHandler:^(UITextField * _Nullable textField) {
                
                textField.placeholder = @"请输入联系人";
                
            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
                
                UITextField *inputTextField = alertController.textFields.firstObject;
                if (inputTextField.text.length > 0) {
                    
                    [parameters setObject:inputTextField.text forKey:@"empName"];
                    [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:2];
                    [rootView.qh_tableView reloadData];
                }
            } completion:nil];
        }
            break;
        case 3: {
            
            /// 联系电话
            [self qh_alertWithTitle:@"请输入联系电话" message:nil inputHandler:^(UITextField * _Nullable textField) {
                
                textField.placeholder = @"请输入联系电话";
                textField.keyboardType = UIKeyboardTypeNumberPad;
                
            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
                
                UITextField *inputTextField = alertController.textFields.firstObject;
                if (inputTextField.text.length > 0) {
                    
                    [parameters setObject:inputTextField.text forKey:@"phoneNum"];
                    [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:3];
                    [rootView.qh_tableView reloadData];
                }
            } completion:nil];
        }
            break;
        case 4: {
            
            /// 身份证号
            [self qh_alertWithTitle:@"请输入身份证号" message:nil inputHandler:^(UITextField * _Nullable textField) {
                
                textField.placeholder = @"请输入身份证号";
                textField.keyboardType = UIKeyboardTypeNumberPad;
            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
                
                UITextField *inputTextField = alertController.textFields.firstObject;
                if (inputTextField.text.length > 0) {
                    
                    [parameters setObject:inputTextField.text forKey:@"busIdCard"];
                    [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:4];
                    [rootView.qh_tableView reloadData];
                }
            } completion:nil];
        }
            break;
        case 5: {
            
            /// 营业执照编号
            [self qh_alertWithTitle:@"请输入身份证号" message:nil inputHandler:^(UITextField * _Nullable textField) {
                
                textField.placeholder = @"请输入身份证号";
                textField.keyboardType = UIKeyboardTypeNumberPad;
            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
                
                UITextField *inputTextField = alertController.textFields.firstObject;
                if (inputTextField.text.length > 0) {
                    
                    [parameters setObject:inputTextField.text forKey:@"busLicNum"];
                    [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:5];
                    [rootView.qh_tableView reloadData];
                }
            } completion:nil];
        }
            break;
        case 6: {
            
            /// 营业执照
            GQH_WEAKSELF;
            TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            imagePickerController.allowTakePicture = YES;
            [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                DLog(@"选择图片完成,上传图片");
                
                if (photos) {
                    
                    GQHTruckImagesCell *cell = [rootView.qh_tableView cellForRowAtIndexPath: indexPath];
                    cell.qh_rightImageView.image = image0 = [photos firstObject];
                    [rootView.qh_tableView reloadData];
                } else {
                    
                    [weakSelf showToastWithText:@"请选择一张营业执照图片"];
                }
            }];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
            break;
        case 7: {
            
            /// 道路运输经营许可证
            GQH_WEAKSELF;
            TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            imagePickerController.allowTakePicture = YES;
            [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                DLog(@"选择图片完成,上传图片");
                
                if (photos) {
                    
                    GQHTruckImagesCell *cell = [rootView.qh_tableView cellForRowAtIndexPath: indexPath];
                    cell.qh_rightImageView.image = image1 = [photos firstObject];
                    [rootView.qh_tableView reloadData];
                } else {
                    
                    [weakSelf showToastWithText:@"请选择一张道路运输经营许可证图片"];
                }
            }];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}

-(void)qh_checkAgreement {
    DLog(@"查看平台认证协议");
    
    GQHAgreementController *agreementController = [[GQHAgreementController alloc] init];
    agreementController.qh_agreementType = GQHAgreementTypeAuthorization;
    [self presentViewController:agreementController animated:YES completion:nil];
}

- (void)qh_submitInformation {
    DLog(@"提交认证信息");
    
    NSArray * keys = @[@"companyName",
                       @"companyAdd",
                       @"empName",
                       @"phoneNum",
                       @"busIdCard",
                       @"busLicNum"];
    for (int i = 0; i < keys.count; i ++)
    {
        [parameters setObject:rootView.qh_contentArray[i] forKey:keys[i]];
    }
    
    if (![parameters objectForKey:@"userId"]) {
        
        [self showToastWithText:@"用户信息出错"];
        return;
    }
    
    if (![parameters objectForKey:@"companyName"]) {
        
        [self showToastWithText:@"请输入公司名称"];
        return;
    }
    
    if (![parameters objectForKey:@"companyAdd"]) {
        
        [self showToastWithText:@"请输入公司地址"];
        return;
    }
    
    if (![parameters objectForKey:@"empName"]) {
        
        [self showToastWithText:@"请输入联系人姓名"];
        return;
    }
    
    if (![parameters objectForKey:@"phoneNum"]) {
        
        [self showToastWithText:@"请输入联系电话"];
        return;
    }
    
    if (![[parameters objectForKey:@"phoneNum"] qh_isValidMobile]) {
        
        [self showToastWithText:@"请输入有效的联系电话"];
        return;
    }
    
    if (![parameters objectForKey:@"busIdCard"]) {
        
        [self showToastWithText:@"请输入身份证号"];
        return;
    }
    
    if (![[parameters objectForKey:@"busIdCard"] qh_isValidIdentityCardNo]) {
        
        [self showToastWithText:@"请输入有效的身份证号"];
        return;
    }
    
    if (![parameters objectForKey:@"busLicNum"]) {
        
        [self showToastWithText:@"请输入营业执照编号"];
        return;
    }
    
    if (!image0) {
        
        [self showToastWithText:@"请选择一张营业执照图片"];
        return;
    }
    
    if (!image1) {
        
        [self showToastWithText:@"请选择一张道路运输经营许可证图片"];
        return;
    }
    
    [self uploadImagesWithSuccess:^(NSNumber *code, NSString *message, NSDictionary *data) {
        
        if (0 == [code integerValue]) {
            
            [[NSUserDefaults standardUserDefaults] setObject:@"02" forKey:USER_STATUS];
            [self showToastWithText:@"认证信息提交成功"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popToRootViewControllerAnimated:YES];
            });
        } else {
            
            [self showToastWithText:message];
        }
    }];
}

#pragma mark --Delegate

#pragma mark --TargetMethod

#pragma mark --PrivateMethod
/// 上传图片
- (void)uploadImagesWithSuccess:(void(^)(NSNumber *code, NSString *message, NSDictionary *data))success {
    
    NSString *APIURLString = [[NSString qh_APIURLString] stringByAppendingPathComponent:@"/myInformation/1/LogisticsCom"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    [manager POST:APIURLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *image0Data = UIImagePNGRepresentation(image0);
        NSData *image1Data = UIImagePNGRepresentation(image1);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmssSSS";
        NSString *name = [formatter stringFromDate:[NSDate date]];
        
        NSString *file0Name = [NSString stringWithFormat:@"%@0.png", name];
        NSString *file1Name = [NSString stringWithFormat:@"%@1.png", name];
        
        
        [formData appendPartWithFileData:image0Data name:@"businessLicPhoto" fileName:file0Name mimeType:@"image/png"];
        [formData appendPartWithFileData:image1Data name:@"roadTraBuLic" fileName:file1Name mimeType:@"image/png"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DLog(@"%@",responseObject);
        
        if (success) {
            
            NSNumber *responseCode = [responseObject objectForKey:@"code"];
            NSString *responseMessage = [responseObject objectForKey:@"msg"];
            NSDictionary *responseData = [responseObject objectForKey:@"data"];
            
            success(responseCode,responseMessage,responseData);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
    }];
}
#pragma mark --Setter

#pragma mark --Getter

#pragma mark --View

@end
